<template>
  <div class="session-detail">
    <!-- 头部导航 -->
    <div class="header">
      <div class="header-left">
        <el-button @click="$router.push('/history')" icon="ArrowLeft" circle />
        <div class="session-info" v-if="session">
          <h2>{{ session.title }}</h2>
          <p>{{ formatTime(session.lastMessageTime) }} • {{ session.messageCount }} 条消息</p>
        </div>
      </div>
      
      <div class="header-right">
        <el-button 
          v-if="session"
          @click="continueChat" 
          type="primary" 
          icon="ChatLineSquare"
        >
          继续对话
        </el-button>
      </div>
    </div>

    <!-- 消息列表 -->
    <div class="messages-container">
      <div v-if="loading" class="loading">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="error" class="error">
        <el-alert
          title="加载失败"
          :description="error"
          type="error"
          show-icon
          @close="loadMessages"
        />
      </div>
      
      <div v-else-if="messages.length === 0" class="empty">
        <el-empty description="这个会话还没有消息记录" />
      </div>
      
      <div v-else class="messages-list">
        <div
          v-for="message in messages"
          :key="message.messageId"
          :class="['message', message.messageType]"
        >
          <div class="message-avatar">
            <el-avatar
              v-if="message.messageType === 'assistant'"
              :src="currentAgent?.avatarUrl"
              :size="40"
            >
              <el-icon><Avatar /></el-icon>
            </el-avatar>
            <el-avatar v-else :size="40">
              <el-icon><User /></el-icon>
            </el-avatar>
          </div>
          
          <div class="message-content">
            <div class="message-bubble">
              <p>{{ message.content }}</p>
              
              <!-- 音频播放控件 -->
              <div v-if="message.audioUrl" class="audio-controls">
                <el-button
                  :icon="playingMessageId === message.messageId ? 'VideoPause' : 'VideoPlay'"
                  @click="toggleAudioPlayback(message)"
                  size="small"
                  circle
                />
                <span class="audio-duration" v-if="message.audioDuration">
                  {{ formatDuration(message.audioDuration) }}
                </span>
                <el-button
                  icon="Download"
                  @click="downloadAudio(message)"
                  size="small"
                  circle
                  title="下载音频"
                />
              </div>
            </div>
            
            <div class="message-time">
              {{ formatMessageTime(message.createTime) }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { chatApi, agentApi } from '@/api'
import type { ChatSession, ChatMessage, AiAgent } from '@/types'

const router = useRouter()
const route = useRoute()

// 响应式数据
const session = ref<ChatSession | null>(null)
const messages = ref<ChatMessage[]>([])
const currentAgent = ref<AiAgent | null>(null)
const loading = ref(true)
const error = ref('')
const playingMessageId = ref<string | null>(null)

// 获取会话ID
const sessionId = computed(() => {
  return route.params.sessionId as string
})

// 组件挂载时加载数据
onMounted(async () => {
  await loadSession()
  await loadMessages()
})

// 加载会话信息
const loadSession = async () => {
  try {
    const response = await chatApi.getSession(sessionId.value)
    if (response.code === 200) {
      session.value = response.data
      
      // 加载对应的智能体信息
      const agentResponse = await agentApi.getAgentById(response.data.agentId)
      if (agentResponse.code === 200) {
        currentAgent.value = agentResponse.data
      }
    } else {
      error.value = response.message || '获取会话信息失败'
    }
  } catch (err) {
    error.value = '网络错误，请检查后端服务是否启动'
    console.error('加载会话信息失败:', err)
  }
}

// 加载消息列表
const loadMessages = async () => {
  try {
    loading.value = true
    error.value = ''
    
    const response = await chatApi.getSessionMessages(sessionId.value)
    if (response.code === 200) {
      messages.value = response.data
    } else {
      error.value = response.message || '获取消息列表失败'
    }
  } catch (err) {
    error.value = '网络错误，请检查后端服务是否启动'
    console.error('加载消息列表失败:', err)
  } finally {
    loading.value = false
  }
}

// 继续对话
const continueChat = () => {
  if (session.value) {
    router.push(`/chat/${session.value.agentId}?sessionId=${session.value.sessionId}`)
  }
}

// 切换音频播放
const toggleAudioPlayback = (message: ChatMessage) => {
  if (playingMessageId.value === message.messageId) {
    // 停止播放
    playingMessageId.value = null
    ElMessage.info('音频播放已停止')
  } else {
    // 开始播放
    playingMessageId.value = message.messageId
    ElMessage.info('音频播放功能开发中')
    // TODO: 实现实际的音频播放逻辑
  }
}

// 下载音频
const downloadAudio = (message: ChatMessage) => {
  if (message.audioUrl) {
    window.open(message.audioUrl, '_blank')
  }
}

// 格式化时间
const formatTime = (timeString: string) => {
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN')
}

// 格式化消息时间
const formatMessageTime = (timeString: string) => {
  const date = new Date(timeString)
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit',
    second: '2-digit'
  })
}

// 格式化音频时长
const formatDuration = (duration: number) => {
  const seconds = Math.floor(duration / 1000)
  return `${seconds}s`
}
</script>

<style scoped>
.session-detail {
  min-height: 100vh;
  background: #f5f6fa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-bottom: 1px solid #e9ecef;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.session-info h2 {
  margin: 0 0 4px 0;
  color: #2c3e50;
  font-size: 1.3rem;
}

.session-info p {
  margin: 0;
  color: #7f8c8d;
  font-size: 0.9rem;
}

.messages-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.loading, .error {
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.empty {
  background: white;
  border-radius: 12px;
  padding: 60px 40px;
  text-align: center;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message {
  display: flex;
  gap: 12px;
  max-width: 70%;
}

.message.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message.assistant {
  align-self: flex-start;
}

.message-content {
  flex: 1;
}

.message-bubble {
  background: white;
  padding: 12px 16px;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #f1f3f4;
}

.message.user .message-bubble {
  background: #409eff;
  color: white;
}

.message-bubble p {
  margin: 0;
  line-height: 1.5;
}

.audio-controls {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
}

.audio-duration {
  font-size: 0.8rem;
  color: #7f8c8d;
}

.message.user .audio-duration {
  color: rgba(255, 255, 255, 0.8);
}

.message-time {
  font-size: 0.8rem;
  color: #bdc3c7;
  margin-top: 4px;
  text-align: right;
}

.message.user .message-time {
  text-align: left;
}

@media (max-width: 768px) {
  .header {
    padding: 16px;
  }
  
  .messages-container {
    padding: 16px;
  }
  
  .message {
    max-width: 85%;
  }
}
</style>
